package cn.itcast.order;

import cn.itcast.feign.client.UserClient;
import cn.itcast.feign.config.DefaultFeignClientConfiguration;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Slf4j
// @EnableEurekaClient只适用于Eureka作为注册中心,
// @EnableDiscoveryClient可以是其他注册中心
// 从Spring Cloud Edgware开始, 这两个注解都是可省略的
// @EnableEurekaClient
@MapperScan("cn.itcast.order.mapper")
// 全局有效, 对多所有微服务的的远程调用都会, 处于一样的配置
@EnableFeignClients(defaultConfiguration = DefaultFeignClientConfiguration.class, clients = {UserClient.class})
// 注意: 当使用了clients就无法使用类路径扫描 basePackages
// @EnableFeignClients(clients = {UserClient.class})
@SpringBootApplication
public class OrderApplication {

    public static void main(String[] args) throws UnknownHostException {
        ConfigurableApplicationContext context = SpringApplication.run(OrderApplication.class, args);

        // 启动完成后, 在控制台提示项目启动成功, 并且输出当前服务对应的swagger接口文档地址
        // environment 可以获取配置文件中的信息
        ConfigurableEnvironment env = context.getEnvironment();
        String appName = env.getProperty("spring.application.name");
        // 会获得局域网的ip, 会不准确
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        //
        String port = StringUtils.isEmpty(env.getProperty("server.port")) ? "8080" : env.getProperty("server.port");

        String protocol = "http";
        log.info(
                "\n----------------------------------------------------------\n\t"
                        + "Application '{}' is running! Access URLs:\n\t" + "Local: \t\t{}://localhost:{}\n\t"
                        + "External: \t{}://{}:{}\n\t"
                        + "Swagger: \t{}://localhost:{}/doc.html\n\t"
                        + "Profile(s): \t{}\n----------------------------------------------------------",
                appName, protocol, port, protocol, hostAddress, port, protocol, port, env.getActiveProfiles());
    }


    /**
     * 创建RestTemplate并注入到spring容器中
     * .  @LoadBalanced 代表负载均衡
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    /**
     * 通过定义IRule试下你可以修改负载均衡规则
     * 这种规则范围是: order-service服务访问任何微服务都要按照下面 随机来
     */
    // @Bean
    public IRule randomRule() {
        return new RandomRule();
    }

}